package com.hnn;

import java.io.BufferedReader;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.LinkedList;
import java.util.List;

/**
 * @author hnn
 * @version 1.0
 * @date 2024-03-21 09:38
 */
public class NioSocketServer {

    private static List<SocketChannel> clients=new LinkedList<SocketChannel>();

    private static void readHandler(SocketChannel client,ByteBuffer buff) throws IOException {
        buff.clear();
        while (true){
            int r= client.read(buff);
            if(r>0) {
                buff.flip();
                byte[] b=new byte[r];
                buff.get(b);
                String str = new String(b);
                System.out.printf("------->接收:%s%n", str);
                buff.flip();
                client.write(buff);
            }else if(r==0) {
                break;
            } else  {
                client.close();
                clients.remove(client);
            }
        }

    }

    public static void main(String[] args) throws Exception {
        ServerSocketChannel socketChannelServer= ServerSocketChannel.open();
        socketChannelServer.configureBlocking(false);
        socketChannelServer.bind(new InetSocketAddress(17777));
        ByteBuffer buff= ByteBuffer.allocate(4096);
        while (true){
            SocketChannel client=socketChannelServer.accept();

            if(client!=null){
                client.configureBlocking(false);
                System.out.printf("-----%s已连接%n", client.getRemoteAddress());
                clients.add(client);
            }

            clients.forEach(c-> {
                try {
                    readHandler(c,buff);
                } catch (IOException e) {

                }
            });
        }


    }
}
